package com.janj.jdbc2;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

//数据修改
import java.sql.*;

public class Demo1 {
    Connection conn = null;
    Statement stat = null;
    ResultSet resu = null;

    @Before
    public void start() {
        try {
            String url = "jdbc:mysql://192.168.65.47:3306/duod9";
            String username = "root";
            String password = "root";
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //修改一条记录
    public int updateToDB(Integer oldId, String newName, Integer newPrice) {
        //表示影响的行数,行数不为0表示成功
        int number = 0;
        try {
            //UPDATE phone SET NAME = 'iphone x ' , price 3588 WHERE id = 7 ;
            //1.准备sql语句
            String sql = "UPDATE phone SET NAME = '" + newName + "',price = " + newPrice + " WHERE id = " + oldId ;
            //2.获取执行者的对象
            Statement stat = conn.createStatement();
            //3.执行sql语句,返回结果
            number = stat.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return number ;
    }

    //测试方法
    @Test
     public void testUpdateToDB(){
        int num = updateToDB(7,"Macbook pro",19998);
        System.out.println(num);
        System.out.println(num == 0 ? "修改失败" : "修改成功");
    }

    @After
    public void end() {
        if (resu != null) {
            try {
                resu.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (stat != null) {
            try {
                stat.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}


